package com.yanqu.road.dao.impl.channelcenter.washe;

import com.yanqu.road.dao.cache.SqlCacheParam;
import com.yanqu.road.dao.impl.TempNoPoolCacheDao;
import com.yanqu.road.entity.activity.washe.config.WasheHonorMomentConfig;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TempWasheHonorMomentConfigDaoImpl extends TempNoPoolCacheDao {

    public TempWasheHonorMomentConfigDaoImpl(String dbParam) {
        super(dbParam);
    }

    private static String getWasheHonorMomentConfigSql = "select * from `t_n_washepvp_lifemax` where `activityId`=?";

    public Map<Integer, List<WasheHonorMomentConfig>> getWasheHonorMomentConfigMap(int activityId) {

        SqlCacheParam sqlCacheParam = getCacheParam(getWasheHonorMomentConfigSql);
        sqlCacheParam.addParam(Integer.class, activityId);
        // 先取缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, List<WasheHonorMomentConfig>>) cacheResult;
        }

        Map<Integer, List<WasheHonorMomentConfig>> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                WasheHonorMomentConfig washeHonorMomentConfig = new WasheHonorMomentConfig();
                washeHonorMomentConfig.setActivityId(rs.getInt("activityId"));
                washeHonorMomentConfig.setHonorMomentId(rs.getInt("honorMomentId"));
                washeHonorMomentConfig.setHonorMomentType(rs.getInt("honorMomentType"));
                washeHonorMomentConfig.setTitle(rs.getString("title"));
                washeHonorMomentConfig.setDesc(rs.getString("desc"));
                washeHonorMomentConfig.setCondition(rs.getInt("condition"));

                map.putIfAbsent(washeHonorMomentConfig.getHonorMomentType(), new ArrayList<>());
                map.get(washeHonorMomentConfig.getHonorMomentType()).add(washeHonorMomentConfig);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }

        for (List<WasheHonorMomentConfig> list : map.values()) {
            list.sort(Comparator.comparing(WasheHonorMomentConfig::getHonorMomentId));
        }

        // 添加缓存
        addCacheResult(sqlCacheParam, map);
        return map;
    }

}
